<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/28 0028
 * Time: 下午 6:13
 */
namespace app\api\service;


use app\admin\model\Store;
use app\admin\model\Ticket;
use app\admin\model\Userbuyticket;
use app\common\Helper;
use app\common\model\Distribution;
use app\common\model\Platformearn;
use app\common\model\Storecustradedetail;
use app\common\model\Storesettlerule;
use app\common\model\Storeuser;
use app\common\model\Userreceivetic;
use think\Db;
use think\Exception;
use think\Loader;
use think\Log;

Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');

/**
 * 处理微信支付回调
 * Class WxNotify
 * @package app\api\service
 */
class WxNotify extends \WxPayNotify{

    //<xml>
    //<appid><![CDATA[wx2421b1c4370ec43b]]></appid>
    //<attach><![CDATA[支付测试]]></attach>
    //<bank_type><![CDATA[CFT]]></bank_type>
    //<fee_type><![CDATA[CNY]]></fee_type>
    //<is_subscribe><![CDATA[Y]]></is_subscribe>
    //<mch_id><![CDATA[10000100]]></mch_id>
    //<nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str>
    //<openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid>
    //<out_trade_no><![CDATA[1409811653]]></out_trade_no>
    //<result_code><![CDATA[SUCCESS]]></result_code>
    //<return_code><![CDATA[SUCCESS]]></return_code>
    //<sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign>
    //<sub_mch_id><![CDATA[10000100]]></sub_mch_id>
    //<time_end><![CDATA[20140903131540]]></time_end>
    //<total_fee>1</total_fee>
    //<trade_type><![CDATA[JSAPI]]></trade_type>
    //<transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id>
    //</xml>
    public function NotifyProcess($data, &$msg){
        if($data['result_code'] == 'SUCCESS'){
            $orderNo = $data['out_trade_no'];
            $paytime = self::timeFormat($data['time_end']);
            Db::startTrans();
            try
            {
                /**
                 * 1.修改订单支付状态
                 * 2.storecustradedetail(店铺客户交易明细表，插入一条记录，减去平台抽成和一二级分销)
                 * 3.platformearn(根据平台抽成规则，插入一条记录)
                 * 3.一二级分销抽成
                 * 4.我的优惠券插入记录
                 */

                $order = Userbuyticket::where('orderNo',$orderNo)->lock(true)->find();
                if($order->status == 0){
                    Userbuyticket::where('id',$order->id)->update(['status'=>1]);
                    //网店铺客户关系表中插入一条数据
                    $this->insertStoreuser($order);
                    //我的优惠券里插入一条记录
                    $this->insertUserreceivetic($order,$paytime);
                    $this->insertStorecustradedetail($order,$paytime);
                }

                Db::commit();

                return true;
            }catch (Exception $ex){
                Db::rollback();
                Log::record($ex);
                return false;
            }
        }else{
            return true;
        }
    }

    private function insertStoreuser($order){
        $Storeuser = Storeuser::where(['userId'=>$order->userId,'storeId'=>$order->storeId])->find();
        if(!$Storeuser){
            $StoreuserModel = new Storeuser();
            $StoreuserModel->userId = $order->userId;
            $StoreuserModel->storeId = $order->storeId;
            $StoreuserModel->save();
        }
    }

    private function insertUserreceivetic($order,$paytime){
       $Userreceivetic = new Userreceivetic();
        $Userreceivetic->id = Helper::getUUID();
        $Userreceivetic->userId = $order->userId;
        $Userreceivetic->storeId = $order->storeId;
        $Userreceivetic->ticketId = $order->ticketId;
        $Userreceivetic->receiveTicketTime = $paytime;
        $Userreceivetic->save();
        //优惠券的剩余数量减1
        Ticket::where('id',$order->ticketId)->setDec('remainGross',1);
    }

    private function insertStorecustradedetail($order,$paytime){
        //判断是否有上级分销 两级分销
        $pingtaiExtract = 0;
        $yijimoney = 0;
        $erjimoney = 0;
        $Storesettlerule = Storesettlerule::where(true)->find();
        $Member = \app\common\model\Member::get($order->userId);
        $Ticket = Ticket::get($order->ticketId);
        if($Member && $Member->boss && $Member->boss!='undefined'){
            $boosuser = \app\common\model\Member::get($Member->boss);
            //有上级（如果有上级 至少有一级分销）
            if($Ticket->firstCommission>0){
                $yijimoney = $Ticket->firstCommission;
                //分销记录
                $Distribution = new Distribution();
                $Distribution->id = Helper::getUUID();
                $Distribution->ticketId = $order->ticketId;
                $Distribution->memberId = $Member->id;
                $Distribution->bossId = $Member->boss;
                $Distribution->type = 1;
                $Distribution->money = $yijimoney;
                $Distribution->orderNo = $order->orderNo;
                $Distribution->createOper = $Member->id;
                $Distribution->save();
                //更新上级分销佣金
                $boosuser->setInc('distributeComm',$yijimoney);
            }
            if($Member->grade == 2){
                //有二级分销
                if($Ticket->secCommission>0){
                    $erjimoney = $Ticket->secCommission;
                    //如果有上上级则更新上上级分销佣金
                    $dingjiboosuser = \app\common\model\Member::get($boosuser->boss);
                    $dingjiboosuser->setInc('distributeComm',$erjimoney);
                }
            }

        }
        if($Storesettlerule->royaltyRate>0){
            //平台收益
            $pingtaiExtract = $order->money * ($Storesettlerule->royaltyRate/100);
            $Platformearn = new Platformearn();
            $Platformearn->id = Helper::getUUID();
            $Platformearn->ticketId = $order->ticketId;
            $Platformearn->orderNo = $order->orderNo;
            $Platformearn->earnings = $pingtaiExtract;
            $Platformearn->createOper = $order->userId;
            $Platformearn->save();
        }
        $money = $order->money-$yijimoney-$erjimoney-$pingtaiExtract;
        //此订单店铺收的钱(店铺客户交易明细表)
        $Storecustradedetail = new Storecustradedetail();
        $Storecustradedetail->id = Helper::getUUID();
        $Storecustradedetail->userId = $order->userId;
        $Storecustradedetail->orderNO = $order->orderNo;
        $Storecustradedetail->proceedsMoney = $money;
        $Storecustradedetail->currentStatus = '已支付';
        $Storecustradedetail->proceedsStoreName = $order->storeName;
        $Storecustradedetail->proceedsTime =$paytime;
        $Storecustradedetail->storeId = $order->storeId;
        $Storecustradedetail->proceedsDeclare = $order->ticketId;
        $Storecustradedetail->save();
        $Store = Store::get($order->storeId);
        $Store->setInc('balance',$money);

    }


    public static function timeFormat($time){
        $paytime = substr($time,0,4).'-';
        $paytime .= substr($time,4,2).'-';
        $paytime .= substr($time,6,2);
        $paytime .= ' ';
        $paytime .= substr($time,8,2).':';
        $paytime .= substr($time,10,2).':';
        $paytime .= substr($time,12,2);
        $paytime = date('Y-m-d H:i:s',strtotime($paytime));
        return $paytime;
    }

}